package MyLinkedList;

import jdk.nashorn.internal.objects.NativeJava;

public class MySingleList {
    static class ListNode{
        public int val;
        public ListNode next;

        public ListNode(int val){
            this.val = val;
        }
    }
    public ListNode head;

    public void display(){
        ListNode cur = head;
        while (cur != null){
            System.out.print(cur.val+ " ");
            cur = cur.next;
        }
        System.out.println();
    }

    public int size(){
        int size = 0;
        ListNode cur = head;
        while (cur != null){
            size ++;
            cur = cur.next;
        }
        return size;

    }

    public boolean contains(int key){
        ListNode cur = head;
        while (cur != null){
            if(cur.val == key){
                return true;
            }
            cur = cur.next;
        }
        return false;
    }

    public void addFirst(int data){
        ListNode node = new ListNode(data);
        node.next = head;
        head = node;

    }

    public void addLast(int data){
        ListNode curNode = new ListNode(data);
        if(head == null){
            head = curNode;
            return;
        }
        ListNode node = findLastNode();
        node.next = curNode;
    }

    private ListNode findLastNode() {
        ListNode cur = head;
        while (cur.next != null){
            cur = cur.next;
        }
        return cur;
    }

    public void addIndex(int index,int data){
        if(index < 0 || index > size()){
            System.out.println("index 位置不合法");
            return;
        }
        if(index == 0){
            addFirst(data);
            return;
        }
        if(index == size()){
            addLast(data);
            return;
        }
        ListNode preNode = findPreindex(index);
        ListNode curNode = new ListNode(data);
        curNode.next = preNode.next;
        preNode.next = curNode;

    }

    private ListNode findPreindex(int index) {
        ListNode cur = head;
        while (index - 1 != 0){
            cur = cur.next;
            index--;
        }
        return cur;
    }

    public void remove(int key){
        if (head == null){
            return;
        }
        if(head.val == key){
            head = head.next;
            return;
        }
        ListNode keyNode = findNodeKey(key);
        if(keyNode == null){
            System.out.println("不存在key值");
            return;
        }
        keyNode.next = keyNode.next.next;


    }

    private ListNode findNodeKey(int key) {
        ListNode cur = head;
        while (cur.next != null){
            if(cur.next.val == key){
                return cur;
            }
            cur = cur.next;
        }
        return null;
    }
}
